package com.jy.event.timer;

import com.jy.event.dao.OrderDao;
import com.jy.event.dao.StoreDao;
import com.jy.event.dao.StorePayDao;
import com.jy.event.domain.ElectronicBill;
import com.jy.event.domain.Store;
import com.jy.event.domain.StorePay;
import com.jy.event.enums.OrderPayChannel;
import com.jy.event.service.ElectronicBillService;
import com.jy.event.service.Payservice;
import com.jy.event.service.impl.SaoBeiServiceImpl;
import com.jy.event.util.JodaUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static com.jy.event.enums.OrderPayChannel.HUI_SHANG;

/**
 * Created by lihu on 2017/12/18.
 */
@Slf4j
@Component
public class ElectronicBillTimer {

    @Autowired
    StoreDao storeDao;

    @Autowired
    Payservice payservice;

    @Autowired
    ElectronicBillService electronicBillService;

    @Autowired
    OrderDao orderDao;

    @Autowired
    SaoBeiServiceImpl saoBeiService;
    @Autowired
    private StorePayDao storePayDao;


    @Scheduled(cron = "0 10 4 * * ?") //推迟8小时执行...
    public void electronicBill() {
        log.info("electronicBill start");
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            date = calendar.getTime();
            String newDate = sdf.format(date);
            SimpleDateFormat sgd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sgd.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            String testDate = null;
            Date date1 = null;
            testDate = sgd.format(date);
            try {
                date1 = sgd.parse(testDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            asyncDateBill(newDate, date1);
        } catch (Exception ex) {
            log.error(" electronicBill is error:{}", ex);
        }
    }

    @Scheduled(cron = "0 25 03 14 12 ?") //同步2019年1月10号之后新交易系统的账单...
    public void electronicAllBill() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        /*final Store store = storeDao.findOne("7491518c-4223-11e9-aad8-d332bc8a93eb");
        if (null != store) {
            for (int i = 20190315; i < 20190813; i++) {
                log.info("electronicBill start " + i);
                Date date = formatter.parse(String.valueOf(i));
                saveElectronicBill(String.valueOf(i), date, store);
            }
        }*/
        /*for (int i = 20190315; i < 20190813; i++) {
            log.info("electronicBill start " + i);
            Date date = formatter.parse(String.valueOf(i));
            asyncDateBill(String.valueOf(i), date);
        }*/
        asyncDateBill("20191211", formatter.parse("20191211"));
        asyncDateBill("20191212", formatter.parse("20191212"));
    }

    private void asyncDateBill(String billDate, Date saveDate) {
        List<StorePay> storePays = storePayDao.findAllByMchIdIsNotNullAndStartEnabledIsTrue();
        for (StorePay storePay : storePays) {
            try {
                if (StringUtils.isEmpty(StringUtils.trim(storePay.getMchId())) || storePay.getMchId().length() < 5)
                    continue;
                Store store = storeDao.findOne(storePay.getStoreId());
                if (null == store) continue;
                List<OrderPayChannel> channels = orderDao.findPayChannelByTime(JodaUtils.getStartOfYesterdayDate(), JodaUtils.getEndOfYesterdayDate());
                if (channels.contains(null) && channels.contains(HUI_SHANG)) {
                    channels.remove(null);
                }
                channels.forEach(channel -> {
                    if (null == channel) {
                        saveElectronicBill(billDate, saveDate, store);
                    } else {
                        switch (channel) {
                            case HUI_SHANG:
                                saveElectronicBill(billDate, saveDate, store);
                                break;
                            case JL:
                                break;
                            case SAO_BEI:
                                break;
                            case SUI_XIN_FU:
                                try {
                                    saveSuiXinFuBill(billDate, saveDate, store);
                                } catch (Exception e) {
                                    log.error(" electronicBill run is error:{},store:{}", storePay, e);
                                }
                                break;
                        }
                    }
                });
            } catch (Exception ex) {
                log.error(" electronicBill run is error:{},store:{}", storePay, ex);
            }
        }
    }

    private void saveSuiXinFuBill(String billDate, Date saveDate, Store store) throws Exception {
        StorePay channel = storePayDao.findTop1ByStoreIdAndChannel(store.getId(), OrderPayChannel.SUI_XIN_FU);
        if (null == channel || StringUtils.isBlank(channel.getMchId())) {
            log.error(" electronicBill run is error: can't found channel {}, store:{}", OrderPayChannel.SUI_XIN_FU, store);
            return;
        }
        ElectronicBill electronicBill = payservice.suixinfuElectronicBill(channel, billDate, saveDate);
        if (electronicBill == null) {
            return;
        }
        electronicBillService.saveChack(electronicBill, store.getName());
    }

    private void saveElectronicBill(String billDate, Date saveDate, Store store) {
        StorePay channel = storePayDao.findTop1ByStoreIdAndChannel(store.getId(), OrderPayChannel.HUI_SHANG);
        if (null == channel || StringUtils.isBlank(channel.getMchId())) {
            log.error(" electronicBill run is error: can't found channel {}, store:{}", OrderPayChannel.HUI_SHANG, store);
            return;
        }
        ElectronicBill electronicBill = payservice.electronicBill(store.getId(), channel.getMchId(), channel.getMchKey(), billDate, saveDate);
        if (electronicBill == null) {
            for (int i = 0; i < 3; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    //
                }
                electronicBill = payservice.electronicBill(store.getId(), channel.getMchId(), channel.getMchKey(), billDate, saveDate);
                if (electronicBill != null) {
                    break;
                }
            }
        }
        if (electronicBill == null) {
            return;
        }
        electronicBillService.saveChack(electronicBill, store.getName());
    }
}
